package com.mall.b2c.hessian.impl;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.mall.b2c.enums.OrderStatus;
import com.mall.b2c.hessian.CommentHessian;
import com.mall.b2c.service.CommentService;
import com.mall.b2c.service.OrderItemService;
import com.mall.common.bean.Pager;
import com.mall.common.hessian.impl.BaseHessianImpl;
import com.mall.common.hibernate.Finder;

@Service("b2cCommentHessian")
public class CommentHessianImpl extends BaseHessianImpl implements CommentHessian {
	@Resource private  CommentService commentService;
	@Resource private OrderItemService orderItemService;
	
	@Override
	public String getGoodsCommentPageData(Long memberId, Long goodsId, Integer grade, Integer pageNumber, Integer pageSize) {
		Pager pager = newPager(pageNumber, pageSize);
		String hql = "select new com.mall.b2c.bean.CommentBean(bean) from CommentDomain bean where 1 = 1";
		Finder finder = Finder.create(hql);
		if(memberId != null){
			finder.append(" and bean.member.id = :memberId");
			finder.setParam("memberId", memberId);
		}

		if(grade != null){
			if(grade == 0) {
				finder.append(" and bean.score >= :score").setParam("score", 4);
			} else if(grade == 1) {
				finder.append(" and bean.score between :score1 and :score2")
					.setParam("score1", 2).setParam("score2", 3);
			} else if(grade == 2) {
				finder.append(" and bean.score <= :score").setParam("score", 1);
			}
		}

		if(goodsId != null){
			finder.append(" and bean.goods.id = :goodsId");
			finder.setParam("goodsId", goodsId);
		}

		pager = commentService.findByPagerForHessian(pager, finder);
		return objToJson(pager);
	}
	
	@Override
	public String getGoodsComments(Long memberId, String orderNo, Boolean hasComment, Integer pageNumber, Integer pageSize) {
		Pager pager = newPager(pageNumber, pageSize);
		if(memberId == null) {
			return objToJson(pager);
		}
		Finder finder = Finder.create("select new com.mall.b2c.bean.OrderItemBean(bean) from OrderItemDomain bean where bean.order.orderStatus = :orderStatus");
		finder.setParam("orderStatus", OrderStatus.tradeFinished);
		finder.append(" and bean.order.member.id = :memberId").setParam("memberId", memberId);
		if(StringUtils.isNotBlank(orderNo)) {
			finder.append(" and bean.order.orderNo = :orderNo").setParam("orderNo", orderNo);
		}
		if(hasComment != null) {
			if(hasComment == Boolean.TRUE) {
				finder.append(" and bean.comment is not null");
			} else {
				finder.append(" and bean.comment is null");
			}
		}
		pager = orderItemService.findByPagerForHessian(pager, finder);
		return objToJson(pager);
	}

	@Override
	public void comment(Long memberId, Long orderItemId, Integer score, String content, Boolean anonymous, String ip) {
		commentService.comment(memberId, orderItemId, score, content, anonymous, ip);
	}
}
